package com.example.mybatisplusdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.mybatisplusdemo.mapper.UserMapper;
import com.example.mybatisplusdemo.model.domain.DeliveryAddress;
import com.example.mybatisplusdemo.mapper.DeliveryAddressMapper;
import com.example.mybatisplusdemo.service.IDeliveryAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 收货地址信息 服务实现类
 * </p>
 *
 * @author lqj
 * @since 2025-06-28
 */
@Service
public class DeliveryAddressServiceImpl extends ServiceImpl<DeliveryAddressMapper, DeliveryAddress> implements IDeliveryAddressService {

    @Autowired
    private DeliveryAddressMapper deliveryAddressMapper;

    @Override
    public List<DeliveryAddress> getByUserId(Long userId) {
        return this.lambdaQuery()
                .eq(DeliveryAddress::getUserId, userId)
                .eq(DeliveryAddress::getDeleted, false)
                .orderByDesc(DeliveryAddress::getIsDefault)
                .orderByDesc(DeliveryAddress::getUpdateTime)
                .list();
    }

    @Override
    public void setDefaultAddress(Long userId, Long addressId) {
        // 1. 清除该用户之前的默认地址
        this.lambdaUpdate()
                .eq(DeliveryAddress::getUserId, userId)
                .set(DeliveryAddress::getIsDefault, false)
                .update();

        // 2. 设置当前地址为默认地址
        this.lambdaUpdate()
                .eq(DeliveryAddress::getId, addressId)
                .set(DeliveryAddress::getIsDefault, true)
                .update();
    }

    @Override
    public List<DeliveryAddress> getAddressesByUserId(Long userId) {
        LambdaQueryWrapper<DeliveryAddress> query = new LambdaQueryWrapper<>();
        query.eq(DeliveryAddress::getUserId, userId).eq(DeliveryAddress::getDeleted, false);
        return deliveryAddressMapper.selectList(query);
    }
}
